<?php

namespace app\api\controller\v2;

use app\common\service\agent\SettingService;
use app\model\TakeoutSlider;
use think\facade\Log;
use think\Request;
use think\facade\Db;
use app\common\service\Ele;
use app\common\service\Meituan;

/**
 * 外卖.
 */
class Takeout extends \app\BaseController
{
    protected $middleware = [
        \app\middleware\ApiChannel::class,
        \app\middleware\ApiUserAuthV2::class => ['except' => ['config']],
    ];

    protected function initialize()
    {
//        $this->request->servType = PRODUCT_MEAL_SERV;
//        $this->request->servName = '外卖';
        parent::initialize();
    }

    /**
     * 订单列表
     */
    public function orderList(Request $request)
    {
        $where[] = ['agent_id', '=', $request->agentChannel['agent_id']];
        $where[] = ['user_id', '=', $request->user['id']];

        $params = input('post.');
        if (!empty($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }
        if (empty($params['order_type'])) {
            $where[] = ['order_type', 'in', [1, 2]];
        } else {
            $where[] = ['order_type', '=', $params['order_type']];
        }

        $list = Db::name('takeout_order')
            ->field('order_type, order_id, paytime, payprice, title, status, img')
            ->where($where)
            ->order('id desc')
            ->paginate([
                'page' => $params['page'] ?? 1,
                'list_rows' => $params['list_rows'] ?? 10,
            ])->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['payprice'] = fen2yuan($v['payprice']);
        }

        return success('操作成功', $list);
    }

    /**
     * 首页配置信息.
     */
    public function config(Request $request)
    {
        $agent_id = $request->agentChannel['agent_id'];
        $type = input('type',TakeoutSlider::TYPE_TACKOUT);
        $config = (new SettingService())->getSliderAndVajra($agent_id,$type);
        return success('操作成功',$config);
    }

    /**
     * 饿了么活动列表
     */
    public function ele(Request $request)
    {
        $list = Db::name('takeout_activity')
            ->field('sub_type, title, act_id, intro')
            ->where('agent_id', $request->agentChannel['agent_id'])
            ->where('type', 1)
            ->where('status', 1)
            ->where('is_deleted', 0)
            ->order('sort desc, id desc')
            ->select()
            ->toArray();

        if (empty($list)) {
            return success('操作成功');
        }

        try {

            $ele = new Ele($request->agentChannel['agent_id']);
            // 获取淘宝联盟 pid
//            $pid = \app\common\model\AlimamaPid::getPid($request->agentChannel['agent_id'], $request->user['id']);

           $pid = \app\common\model\AlimamaPid::getPIdByAgentId($request->agentChannel['agent_id']);

            if (false === $pid) {
                return fail('链接生成失败，请稍后重试'.$request->agentChannel['agent_id'].'---'.$request->user['id']);
            }
        } catch (\Exception $e) {
            return fail($e->getMessage());
        }

        $res = [];
        foreach ($list as $k => $v) {
            $data = $ele->activity_info_get($pid, $v['act_id']);
//            Log::info($data);
            if (false === $data) {
                continue;
            }
            if (!empty($data['data']['short_click_url'])) {
                $res[] = [
                    'sub_type' => $v['sub_type'],
                    'title' => $v['title'],
                    'click_url' => $data['data']['short_click_url'],
                    'intro' => $v['intro'],
                ];
            }
        }
        unset($list);

        return success('操作成功', $res);
    }

    /**
     * 美团活动列表
     */
    public function meituan(Request $request)
    {

        $list = Db::name('takeout_activity')
            ->field('title, act_id, intro, sub_type')
            ->where('type', 2)
            ->where('agent_id',0)
            ->where('status', 1)
            ->where('is_deleted', 0)
            ->order('sort desc, id desc')
            ->select()
            ->toArray();


        if (empty($list)) {
            return success('操作成功1');
        }
        try {

            $meituan = new Meituan($request->agentChannel['agent_id']);

        } catch (\Exception $e) {
            return fail($e->getMessage());
        }

        $res = [];
        // $err = [];
        foreach ($list as $k => $v) {
            $url = $meituan->generateLink([
                'user_id' => $request->user['id'],
                'agent_id' => $request->agentChannel['agent_id'],
                'channel_id' => $request->agentChannel['id'],
                'act_id' => $v['act_id'],
                'from' =>input('from')
            ]);
            if (false === $url) {
                // $err[] = $meituan->getError();
                continue;
            }
            $res[] = [
                'sub_type' => $v['sub_type'],
                'title' => $v['title'],
                'click_url' => $url,
                'intro' => $v['intro'],
            ];
        }
        unset($list);
        // $res['err'] = $err;

        return success('操作成功2', $res);
    }

    /**
     * 美团优选
     *
     * @param   $lng            经度
     * @param   $lat            纬度
     * @param   $page           当前页
     * @param   $size           每页结果数
     */
    public function meituanYouxuan(Request $request)
    {
        try {
            $meituan = new Meituan($request->agentChannel['agent_id']);
        } catch (\Exception $e) {
            return fail($e->getMessage());
        }
        $params = input('post.');
        $params['user_id'] = $request->user['id'];
        if (empty($params['lng'])) {
            $params['lng'] = '118.05122';
            $params['lat'] = '24.58038';
        }

        $res = $meituan->skuQuery($params);
        if (false === $res) {
            return fail('获取失败');
        }
        return success('操作成功', $res);
    }
}
